package com.cwj.blog.module.add

import android.app.Activity
import android.text.TextUtils
import android.view.View
import android.view.View.OnClickListener
import com.cwj.blog.R
import com.cwj.blog.base.BaseActivity
import com.cwj.blog.bean.SuccessBean
import com.cwj.blog.databinding.ActivityAddBlogBinding
import com.cwj.blog.util.LoadingDialog
import com.yechaoa.yutils.ToastUtil

class AddBlogActivity : BaseActivity<ActivityAddBlogBinding, AddBlogPrensenter>(), AddBlogView,
    OnClickListener {

    private var loadingDialog: LoadingDialog? = null

    override fun createPresenter(): AddBlogPrensenter {
        return AddBlogPrensenter(this)
    }

    override fun initView() {
        loadingDialog = LoadingDialog(this@AddBlogActivity, "")
        viewBinding.btnSubmit.setOnClickListener(this)
    }

    override fun initData() {

    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.btnSubmit -> {
                if (TextUtils.isEmpty(viewBinding.etTitle.text.toString().trim())) {
                    ToastUtil.showCenter("标题不能为空")
                } else if (TextUtils.isEmpty(viewBinding.etUrl.text.toString().trim())) {
                    ToastUtil.showCenter("文章链接不能为空")
                } else if (!viewBinding.etUrl.text.toString().trim().startsWith("http://") &&
                    !viewBinding.etUrl.text.toString().trim().startsWith("https://")
                ) {
                    ToastUtil.showCenter("请输入以http或https开头的链接")
                } else {
                    val map: MutableMap<String, Any> = HashMap()
                    map["title"] = viewBinding.etTitle.text.toString().trim()
                    map["url"] = viewBinding.etUrl.text.toString().trim()

                    loadingDialog?.show()
                    //博客添加
                    presenter.addBlog(map)
                }
            }
        }
    }

    override fun error(msg: String?) {
        loadingDialog?.dismiss()
        ToastUtil.showCenter(msg)
    }

    override fun addBlogSuccess(successBean: SuccessBean?) {
        loadingDialog?.dismiss()
        ToastUtil.showCenter(successBean!!.msg)
        setResult(Activity.RESULT_OK)
        finish()
    }
}